//
//  GCDTimer.swift
//  AIRingtone
//
//  Created by 100Years on 2025/3/21.
//

import Foundation

public class TSGCDTimer {
    private var timer: DispatchSourceTimer?
    public private(set) var isRunning: Bool = false

    
    public init() {
        
    }
    
    /// 启动定时器
    /// - Parameters:
    ///   - interval: 时间间隔（秒）
    ///   - repeats: 是否重复
    ///   - queue: 执行队列（默认主队列）
    ///   - handler: 定时器触发时的回调
    public func start(interval: TimeInterval, repeats: Bool = true, queue: DispatchQueue = .main, handler: @escaping () -> Void) {
        // 如果定时器已经存在，先停止
        stop()

        // 创建定时器
        timer = DispatchSource.makeTimerSource(queue: queue)
        let deadline: DispatchTime = .now() + interval
        let repeating: DispatchTimeInterval = repeats ? .seconds(Int(interval)) : .never

        timer?.schedule(deadline: deadline, repeating: repeating)
        timer?.setEventHandler(handler: handler)
        timer?.resume()

        isRunning = true
    }

    /// 停止定时器
    public func stop() {
        if isRunning {
            timer?.cancel()
            timer = nil
            isRunning = false
        }
    }

    /// 释放定时器
    deinit {
        stop()
        dePrint("GCDTimer deinit")
    }
}
